package com.ads.tpgrupo4.server.service.generarFacturas;

import java.util.List;

import com.ads.tpgrupo4.domain.cpr.facturacion.Factura;
import com.ads.tpgrupo4.server.config.Config;
import com.ads.tpgrupo4.server.fileserver.FileServer;
import com.ads.tpgrupo4.server.remote.PersistenceService;
import com.ads.tpgrupo4.server.service.generarCotizacionesPendientes.OutputFilesUrlUtils;
import com.ads.tpgrupo4.server.service.generarFacturasAClientes.Facturador;
import com.ads.tpgrupo4.server.service.generarFacturasAClientes.GenerarFacturasAClientesServiceException;
import com.ads.tpgrupo4.server.utils.UriUtils;
import com.ads.tpgrupo4.server.xml.XmlSource;
import com.ads.tpgrupo4.server.xml.mappers.FacturaXmlMapper;

public class GenerarFacturasService {
	
	private Facturador facturador = Facturador.getInstance();
	
	private PersistenceService persistenceService = PersistenceService.getInstance();
	
	private static GenerarFacturasService instance;
	
	public static GenerarFacturasService getInstance() {

		if (instance == null) {
			instance = new GenerarFacturasService();
		}
		
		return instance;
	}
	
	private GenerarFacturasService() {
	}
	
	public void generarFacturas() {
		
		try {
			
			final List<Factura> facturas = this.facturador.generarFacturas();
			
			this.persistenceService.saveFacturas(facturas);
			
			for (final Factura factura : facturas) {
				
				this.trySaveToFileSystem(factura);
			}
			
		} catch (final Exception e) {
			throw new GenerarFacturasAClientesServiceException(e);
		}
	}
	
	private void trySaveToFileSystem(final Factura factura) {
		
		try {		

			final String fileName = OutputFilesUrlUtils.getExpectedFileNameFor(factura);
			final String filePath = UriUtils.buildPath(Config.getInstance().getGeneratedFilesContainerDir(), fileName);
			
			final XmlSource asXml = FacturaXmlMapper.getInstance().map(factura);
			
			FileServer.createFile(asXml.toString(), filePath);
		
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

}
